package com.guaoran.distributed.message.kafka.group;

import com.guaoran.distributed.message.kafka.common.CommonUtil;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.util.Collections;
import java.util.Properties;

/**
 * @author : guaoran
 * @Description : <br/>
 *  消费端消息接受
 * @date :2018/11/9 16:00
 */
public class KafkaConsumerGroup2Demo extends Thread {
    private final static String CONNECT_URL = CommonUtil.BOOTSTRAP_SERVERS_CONFIG;
    private final KafkaConsumer<Integer,String> consumer;
    public KafkaConsumerGroup2Demo(String topic){
        Properties properties = new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,CONNECT_URL);
        //分组id
        properties.put(ConsumerConfig.GROUP_ID_CONFIG,"kafka-group1");
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,"true");
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.IntegerDeserializer");
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.StringDeserializer");
        properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,"earliest");
        consumer = new KafkaConsumer<Integer, String>(properties);
        consumer.subscribe(Collections.singletonList(topic));
    }

    @Override
    public void run() {
        while(true){
            ConsumerRecords<Integer,String> consumerRecords = consumer.poll(1000);
            for (ConsumerRecord r :consumerRecords) {
                System.out.println("consumer...receive.."+r.value());
            }
        }
    }

    public static void main(String[] args) {
        new KafkaConsumerGroup2Demo("group-test").start();
    }
}
